package org.budo.graph.service.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.budo.graph.Constant;
import org.budo.support.freemarker.FreemarkerUtil;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.servlet.util.QueryStringUtil;
import org.budo.support.spring.io.util.ResourceUtil;
import org.springframework.context.ApplicationContext;

/**
 * @author limingwei
 */
public class SessionRequestUtil {
    private static final String _BUDO_GRAPH_SERVICE = "org.budo.graph.service.BudoGraphService.dubboProviderMetadata()";

    private static final Map<String, Set<String>> _SESSION_TO_REQUEST_MAP = new HashMap<String, Set<String>>();

    /**
     * @see java.util.HashMap#containsKey(Object)
     * @see java.util.HashMap#put(Object, Object)
     */
    public static void recordSessionRequest(String requestSessionId, String requestURI) {
        if (null == requestSessionId || null == requestURI || requestURI.equals(_BUDO_GRAPH_SERVICE)) {
            return; // 非业务接口 排除 跳过
        }

        Set<String> set = _SESSION_TO_REQUEST_MAP.get(requestSessionId);
        if (null != set) { // 已有set
            if (set.contains(requestURI)) { // 已
                return;
            }

            set.add(requestURI);
            return;
        }

        Set<String> newSet = new HashSet<String>();
        newSet.add(requestURI);
        _SESSION_TO_REQUEST_MAP.put(requestSessionId, newSet);
    }

    public static String writeSessionRequestResponse(ApplicationContext applicationContext, String url) {
        Map<String, String> parameters = QueryStringUtil.queryStringToStringMap(url);
        String sessionId = parameters.get("sessionId");

        if (null == sessionId) {
            return "SESSION_ID_IS_NULL";
        }

        Set<String> sessionRequestSet = _SESSION_TO_REQUEST_MAP.get(sessionId);

        Map<String, Object> map = MapUtil.stringObjectMap("sessionRequestSet", sessionRequestSet, "sessionId", sessionId);
        String inputString = ResourceUtil.classPathResourceInputStreamToString(Constant.GRAPH_TEMPLATE_PATH + "/session-request.htm");

        return FreemarkerUtil.freemarkerRender(inputString, map);
    }

    public static Boolean hasSessionRequest(String sessionId) {
        if (null == _SESSION_TO_REQUEST_MAP || sessionId.isEmpty() || null == sessionId || sessionId.isEmpty()) {
            return false;
        }

        Set<String> set = _SESSION_TO_REQUEST_MAP.get(sessionId);
        return null != set && !set.isEmpty();
    }
}